import { useMemo } from "react";
import { URLSearchParamsInit, useSearchParams } from "react-router-dom";
import { cleanObject } from "utils";

// 返回页面url中，指定键的参数值
// 需要给初始值限制为{[key]:string}的类型
export const useUrlQueryParam = <K extends string>(keys: K[]) => {
  const [searchParams, setSearchParams] = useSearchParams();
  return [
    // 每次返回一个新的对象会导致无限render，使用useMemo来解决
    // 只有在searchParams改变时才进行运算
    useMemo(
      () =>
        keys.reduce((prev: { [key in K]: string }, key: K) => {
          return { ...prev, [key]: searchParams.get(key) || "" };
        }, {} as { [key in K]: string }),
      // eslint-disable-next-line react-hooks/exhaustive-deps
      [searchParams]
    ),
    (param: Partial<{ [key in K]: unknown }>) => {
      // iterator遍历对象：https://codesandbox.io/s/upbeat-wood-bum3j?file=/src/index.js
      // 读取现在url的参数，然后把它变成普通对象，加上传入的对象
      const obj = cleanObject({
        ...Object.fromEntries(searchParams),
        ...param,
      }) as URLSearchParamsInit;
      return setSearchParams(obj);
    },
  ] as const;
};
